package pool

import (
	"context"
	"fmt"
	"github.com/go-pkgz/syncs"
	"sync"
	"sync/atomic"
)

type Student struct {
	Name   string
	Age    int
	Remark [1024]byte
}

func read() {
	m := make(map[int]*Student)
	var wg sync.WaitGroup
	wg.Add(1)
	for i := 0; i < 100; i++ {
		m[i] = &Student{Name: "face", Age: 25}
	}

	go func() {
		for i := 0; i < 100; i++ {
			stu := m[i]
			fmt.Println(stu)
		}
		wg.Done()
	}()
	wg.Wait()
}

func poolRead() {
	var wg sync.WaitGroup
	wg.Add(200)
	start := false
	pool := sync.Pool{
		New: func() interface{} {
			return &Student{Name: "face", Age: 25}
		},
	}
	go func() {
		for {
			for i := 0; i < 100 && start; i++ {
				stu := pool.Get().(*Student)
				fmt.Println(stu)
				wg.Done()
				if i == 99 {
					return
				}

			}
		}
	}()

	for i := 0; i < 100; i++ {
		start = true
		pool.Put(&Student{Name: "face", Age: i})
		wg.Done()
	}

	wg.Wait()
}

func asyncPool(task, total int) uint32 {
	// 执行1000个子任务，只会有10个goroutine去执行
	swg := syncs.NewSizedGroup(task)
	var c uint32

	for i := 0; i < total; i++ {
		swg.Go(func(ctx context.Context) {
			atomic.AddUint32(&c, 1)
		})
	}
	swg.Wait()
	return c
}
